package com.ruoyi.project.comp.h5;

import com.ruoyi.common.oss.OSSUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.comp.comment.domain.CompComment;
import com.ruoyi.project.comp.comment.service.ICompCommentService;
import com.ruoyi.project.comp.file.domain.CompWorkFile;
import com.ruoyi.project.comp.file.service.ICompWorkFileService;
import com.ruoyi.project.comp.like.domain.CompLike;
import com.ruoyi.project.comp.like.mapper.CompLikeMapper;
import com.ruoyi.project.comp.like.service.ICompLikeService;
import com.ruoyi.project.comp.setting.domain.CompSetting;
import com.ruoyi.project.comp.setting.service.ICompSettingService;
import com.ruoyi.project.comp.share.domain.CompShare;
import com.ruoyi.project.comp.share.service.ICompShareService;
import com.ruoyi.project.comp.work.domain.CompWork;
import com.ruoyi.project.comp.work.service.ICompWorkService;
import com.ruoyi.project.system.score.domain.CompScore;
import com.ruoyi.project.system.score.service.ICompScoreService;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.Principal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 作品Controller
 *
 * @author ruoyi
 * @date 2025-11-02
 */
@Controller
@RequestMapping("/h5/comp/work")
public class H5CompWorkController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(com.ruoyi.project.comp.work.controller.CompWorkController.class);

    private String prefix = "h5/comp/work";

    @Autowired
    private ICompWorkService compWorkService;

    @Autowired
    private ICompWorkFileService compWorkFileService;

    @Autowired
    private ICompLikeService compLikeService;

    @Autowired
    private ICompShareService compShareService;

    @Autowired
    private ICompCommentService compCommentService;

    @Autowired
    private OSSUtils ossUtils;

    @Autowired
    private ICompSettingService compSettingService;
    @Autowired
    private ICompScoreService compScoreService;


    @Autowired
    private CompLikeMapper compLikeMapper;

    @GetMapping()
    public String work() {
        return prefix + "/work";
    }


    /**
     * 新增作品
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存作品
     */
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestBody CompWork compWork, HttpServletRequest request) {

        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            return AjaxResult.error("请先微信授权登录");
        }
        compWork.setParticipantUserId(loginUser.getUserId());
        int count = compWorkService.insertCompWork(compWork);
        return toAjax(count);
    }


    @GetMapping("/rank/data")
    @ResponseBody
    public List<CompWork> getRank(@RequestParam String rankType) {
        CompWork queryCompWork = new CompWork();
        queryCompWork.setStatus(1L);
        List<CompWork> workList = compWorkService.selectCompWorkList(queryCompWork);
        if ("totalScore".equals(rankType)) {// 综合得分
            workList = workList.stream()
                    .sorted(Comparator.comparing(CompWork::getTotalScore ,
                                    Comparator.nullsLast(Comparator.reverseOrder()))
                            .thenComparing(CompWork::getId)) // 得分相同时，按ID排序（可选）
                    .collect(Collectors.toList()); // 转换为 List
        }
        if ("likeCount".equals(rankType)) {// 综合得分
            workList = workList.stream()
                    .sorted(Comparator.comparing(CompWork::getLikeCount,
                                    Comparator.nullsLast(Comparator.reverseOrder()))
                            .thenComparing(CompWork::getId)) // 得分相同时，按ID排序（可选）
                    .collect(Collectors.toList()); // 转换为 List
        }
        if ("lookCount".equals(rankType)) {// 综合得分
            workList = workList.stream()
                    .sorted(Comparator.comparing(CompWork::getLookCount,
                                    Comparator.nullsLast(Comparator.reverseOrder()))
                            .thenComparing(CompWork::getId)) // 得分相同时，按ID排序（可选）
                    .collect(Collectors.toList()); // 转换为 List
        }
        if ("shareCount".equals(rankType)) {// 综合得分
            workList = workList.stream()
                    .sorted(Comparator.comparing(CompWork::getShareCount,
                                    Comparator.nullsLast(Comparator.reverseOrder()))
                            .thenComparing(CompWork::getId)) // 得分相同时，按ID排序（可选）
                    .collect(Collectors.toList()); // 转换为 List
        }
        if ("studentScore".equals(rankType)) {// 综合得分
            workList = workList.stream()
                    .sorted(Comparator.comparing(CompWork::getStudentScore,
                                    Comparator.nullsLast(Comparator.reverseOrder()))
                            .thenComparing(CompWork::getId)) // 得分相同时，按ID排序（可选）
                    .collect(Collectors.toList()); // 转换为 List
        }
        if ("teacherScore".equals(rankType)) {// 综合得分
            workList = workList.stream()
                    .sorted(Comparator.comparing(CompWork::getTeacherScore,
                                    Comparator.nullsLast(Comparator.reverseOrder()))
                            .thenComparing(CompWork::getId)) // 得分相同时，按ID排序（可选）
                    .collect(Collectors.toList()); // 转换为 List
        }


        for (int i = 0; i < workList.size(); i++) {
            CompWork compWork = workList.get(i);
            compWork.setIndex(i + 1);
        }
        return workList;
    }


    // 统一返回类型（假设AjaxResult与ResultVO功能类似，若不兼容可调整泛型）
    @PostMapping("/submitScore")
    @ResponseBody
    public AjaxResult submitScore(@RequestParam Integer workId,
                                  @RequestParam String scoreType, @RequestParam BigDecimal score, HttpServletRequest request) {
        try {
            User loginUser = (User) request.getSession().getAttribute("loginUser");
            if (loginUser == null) {
                return AjaxResult.error("请先微信授权登录");
            }
            String userId = String.valueOf(loginUser.getUserId());// TODO
            CompWork work = new CompWork();
            work.setId(Long.valueOf(workId));
            if ("student".equals(scoreType)) {
                work.setStudentScore(score);
            } else {
                work.setTeacherScore(score);
            }
            // 重新计算综合得分（示例：学生30% + 教师50% + 大众20%）
            CompWork oldWork = compWorkService.selectCompWorkById(Long.valueOf(workId));
            BigDecimal total = score.multiply("student".equals(scoreType) ? new BigDecimal("0.3") : new BigDecimal("0.5"))
                    .add(oldWork.getPublicScore().multiply(new BigDecimal("0.2")))
                    .add("student".equals(scoreType) ? oldWork.getTeacherScore().multiply(new BigDecimal("0.5"))
                            : oldWork.getStudentScore().multiply(new BigDecimal("0.3")));
            work.setTotalScore(total.setScale(2, BigDecimal.ROUND_HALF_UP));
            compWorkService.updateCompWork(work);

            CompScore compScore = new CompScore();
            compScore.setUserId(Long.valueOf(userId));
            compScore.setWorkId(work.getId());
            compScore.setScore(total.setScale(2, BigDecimal.ROUND_HALF_UP));
            compScoreService.insertCompScore(compScore);



            return AjaxResult.success("评分提交成功");
        } catch (Exception exception) {
            return AjaxResult.error("已评过分或参数错误");
        }
    }

    /**
     * 点赞
     * @param workId
     * @return
     */
    @PostMapping("/like")
    @ResponseBody
    public AjaxResult submitLike(@RequestParam Integer workId, HttpServletRequest request) {
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            return AjaxResult.error("请先微信授权登录");
        }
        String userId = String.valueOf(loginUser.getUserId());// TODO
        //boolean repeated = checkTodayLike(workId, userId);

//        1、每个微信账号每天可以给10个作品点赞。
//        2、单个微信账号每天最多可以点赞的总次数为50次。
//        3、每个微信账号每天可以为同一作品点赞5次。
//        4、每次点赞间隔需超过30秒。
        // 检查条件1：每个微信账号每天可以给10个作品点赞
        int distinctWorksCount = compLikeMapper.countDistinctWorksToday(userId);
        if (distinctWorksCount >= 10) {
            return AjaxResult.error("今日已为10个不同作品点赞，无法继续点赞");
        }

        // 检查条件2：单个微信账号每天最多可以点赞的总次数为50次
        int totalLikesCount = compLikeMapper.countTotalLikesToday(userId);
        if (totalLikesCount >= 50) {
            return AjaxResult.error("今日点赞总次数已达50次，无法继续点赞");
        }

        // 检查条件3：每个微信账号每天可以为同一作品点赞5次
        int workLikesCount = compLikeMapper.countWorkLikesToday(workId, userId);
        if (workLikesCount >= 5) {
            return AjaxResult.error("今日已为该作品点赞5次，无法继续点赞");
        }

        // 检查条件4：每次点赞间隔需超过30秒
        Timestamp lastLikeTime = compLikeMapper.getLastLikeTime(userId);
        if (lastLikeTime != null) {
            long currentTime = System.currentTimeMillis();
            long lastTime = lastLikeTime.getTime();
            long interval = (currentTime - lastTime) / 1000; // 转换为秒

            if (interval < 30) {
                return AjaxResult.error("点赞过于频繁，请" + (30 - interval) + "秒后再试");
            }
        }

        // 检查是否今日已点赞（原有逻辑，可根据需要保留或移除）
        //boolean repeated = compLikeMapper.checkTodayLike(workId, userId);
//        boolean repeated = checkTodayLike(workId, userId);
//        if (repeated) {
//            return AjaxResult.error("今日已点赞");
//        }
        addLike(workId, userId);
        return AjaxResult.success("点赞成功");
    }

    /**
     * 转发
     * @param workId
     * @param sharePlatform
     * @return
     */
    @PostMapping("/share")
    @ResponseBody
    public AjaxResult recordShare(@RequestParam Integer workId,
                                  @RequestParam(required = false, defaultValue = "微信") String sharePlatform
            ,HttpServletRequest request) {
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            return AjaxResult.error("请先微信授权登录");
        }
        String userId = String.valueOf(loginUser.getUserId());// TODO
        addShare(workId, userId, sharePlatform);
        return AjaxResult.success("转发记录成功");
    }

    /**
     * 评论
     * @param workId
     * @param content
     * @param pid
     * @return
     */
    @PostMapping("/comment")
    @ResponseBody
    public AjaxResult addComment1(
            @RequestParam Integer workId, @RequestParam String content,
            @RequestParam(required = false) Integer pid,HttpServletRequest request) {
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            return AjaxResult.error("请先微信授权登录");
        }
        String userId = String.valueOf(loginUser.getUserId());// TODO
        // 可添加评论内容校验（如长度限制）
        if (content == null || content.trim().length() == 0) {
            return AjaxResult.error("评论内容不能为空");
        }
        CompComment compComment = new CompComment();
        compComment.setWorkId(Long.valueOf(workId));
        compComment.setUserId(Long.valueOf(userId));
        compComment.setContent(content);
        if(pid != null){
            compComment.setPid(Long.valueOf(pid));
        }
        compCommentService.insertCompComment(compComment);
        return AjaxResult.success("评论发表成功");
    }


    // 检查今日是否已点赞
    public boolean checkTodayLike(Integer workId, String userId) {
        long todayLike = 5;
        CompSetting compSetting = compSettingService.selectCompSettingById(1L);
        if(compSetting != null){
            todayLike = compSetting.getDailyLikeLimit();
        }
        return compLikeService.countTodayLike(workId, userId, new Date()) > todayLike;
    }

    // 添加点赞
    public void addLike(Integer workId, String userId) {
        CompLike like = new CompLike();
        like.setWorkId(Long.valueOf(workId));
        like.setUserId(Long.parseLong(userId));
        like.setLikeTime(new Date());
        compLikeService.insertCompLike(like);
        CompWork compWork = compWorkService.selectCompWorkById(Long.valueOf(workId));
        CompWork upCompWork = new CompWork();
        upCompWork.setId(compWork.getId());
        if(compWork != null && compWork.getLikeCount()  != null){
            upCompWork.setLikeCount(compWork.getLikeCount() + 1);
        }else{
            upCompWork.setLikeCount(1);
        }
        compWorkService.updateCompWork(upCompWork);
    }

    // 记录转发
    public void addShare(Integer workId, String userId, String platform) {
        CompShare share = new CompShare();
        share.setWorkId(Long.valueOf(workId));
        share.setUserId(Long.parseLong(userId));
        share.setShareTime(new Date());
        share.setSharePlatform(platform);
        compShareService.insertCompShare(share);
        CompWork compWork = compWorkService.selectCompWorkById(Long.valueOf(workId));
        CompWork upCompWork = new CompWork();
        upCompWork.setId(compWork.getId());
        Integer shareCount = compWork.getShareCount();
        if(shareCount != null){
            compWork.setShareCount(shareCount + 1);
        }else{
            compWork.setShareCount(1);
        }
        upCompWork.setShareCount(shareCount + 1);
        compWorkService.updateCompWork(upCompWork);
    }

}
